<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>2019/1/19</title>
    <!--好的代码像粥一样,是得用时间和精力熬的。-->
</head>
<body>
  <div id="app">
    <div id="a"></div>
    <div id="b"></div>
    <div id="c"></div>
    <input type="text" id="d">
    <button onclick="vm.fn()">click</button>
  </div>
</body>
<script>
  // 模拟const
  // _const('a', 1);
  // function _const(variable, value) {
  //   Object.defineProperty(window, variable, {
  //     value: value,
  //     Writable: false,
  //     configurable: false,
  //   })
  // }

  //vue数据代理
  var vm = {
    $el: '#app',
    $data: {
      a: 1,
      b: 2,
      c: 3,
      d: '',
    },
    $methods: {
      fn: function () {
        this.a = this.b;
      },
      change(e) {
        this.d = e.target.value;
      }
    }
  };
  function proxy(target, prop) {
    Object.keys(target[prop]).forEach(function (item) {
      Object.defineProperty(target, item, {
        get() {
          return target[prop][item];
        },
        set(newValue) {
          target[prop][item] = newValue;
          update(item);
        }
      })
    })
  }
  function update (id) {
    if (id === 'd') {
      document.getElementById(id).value = vm[id];
    } else {
      document.getElementById(id).innerText = vm[id];
    }
  }
  document.getElementById('d').oninput = function (e) {
    vm.d = e.target.value;
    vm.c = vm.d;
  };
  proxy(vm, '$data'); // vue数据代理
  proxy(vm, '$methods');

</script>
</html>
